package com.example.user.controller;

import com.example.entity.BookDto;
import com.example.entity.JsonData;
import com.example.user.domain.User;
import com.example.user.service.UserService;
import com.example.user.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("user")
public class UserController {
    /**
     * 远程数据接口--服务提供者
     */
    private static final String BOOK_URL = "http://localhost:8082/book/";
    /**
     * 远程服务调用
     */
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private UserService userService;

    /**
     * 获取用户及其书本
     *
     * @param id 用户id
     * @return {@link Object}
     */
    @GetMapping("/{id}")
    public Object getUser(@PathVariable("id") Long id) {
        User user = userService.getUserById(id);
        List forObject = restTemplate.getForObject(BOOK_URL + id, List.class);
        user.setBookDtoList(forObject);
        return JsonData.buildSuccess(user);
    }

    @PostMapping("/login")
    public Object checkLogin(@RequestBody User user) {
        String username = user.getUsername();
        String password = user.getPassword();
        return userService.checkLogin(username, password);
    }

    @PostMapping("/add-book")
    public Object addBook(@RequestBody BookDto book, HttpServletRequest request) {
        String token = request.getHeader("token");
        Integer userId = Integer.valueOf(getUserIdByToken(token));
        book.setUserId(userId);
        return JsonData.buildSuccess(restTemplate.postForObject(BOOK_URL + "add", book, int.class));
    }

    @DeleteMapping("/remove-book/{bookId}")
    public Object removeBook(@PathVariable("bookId") Long bookId) {
        restTemplate.delete(BOOK_URL + "remove/" + bookId, int.class);
        return JsonData.buildSuccess();
    }

    @PostMapping("/update-book")
    public Object updateBookByBookId(@RequestBody BookDto book, HttpServletRequest request) {
        String token = request.getHeader("token");
        Integer userId = Integer.valueOf(getUserIdByToken(token));
        book.setUserId(userId);
        return JsonData.buildSuccess(restTemplate.postForObject(BOOK_URL + "update", book, int.class));
    }

    @GetMapping("/getBookByBookId/{id}")
    public Object getBookByBookId(@PathVariable("id") Long id) {
        BookDto forObject = restTemplate.getForObject(BOOK_URL + "getBookByBookId/" + id, BookDto.class);
        return JsonData.buildSuccess(forObject);
    }

    @GetMapping("/getBookByBookName/{name}")
    public Object getBookByBookName(@PathVariable("name") String name, HttpServletRequest request) {
        String token = request.getHeader("token");
        Integer userId = Integer.valueOf(getUserIdByToken(token));
        List forObject = restTemplate.getForObject(BOOK_URL + "getBookByBookName/" + name + "/" + userId, List.class);
        return JsonData.buildSuccess(forObject);
    }

    public String getUserIdByToken(String token) {
        Claims claims = null;
        try {
            claims = JwtUtil.parseJWT(token);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return claims.getSubject().split("login:")[1];
    }
}
